package com.ruiysoft.controller.sys;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruiysoft.constant.IdentityConst;
import com.ruiysoft.controller.integral.vo.IntegralRechargeVo;
import com.ruiysoft.controller.sys.api.MicroprogramApi;
import com.ruiysoft.controller.sys.api.service.MicroprogramApiService;
import com.ruiysoft.controller.sys.dto.PreorderDto;
import com.ruiysoft.controller.sys.dto.ShopDesignDto;
import com.ruiysoft.controller.sys.dto.ShopDistributionDto;
import com.ruiysoft.controller.sys.dto.ShopDto;
import com.ruiysoft.controller.sys.dto.UserDto;
import com.ruiysoft.controller.sys.dto.WeChatInfoDto;
import com.ruiysoft.controller.sys.res.BrowsedShopResponse;
import com.ruiysoft.controller.sys.res.PreorderResponse;
import com.ruiysoft.controller.sys.res.ShopPersonnelResponse;
import com.ruiysoft.controller.sys.res.ShopResponse;
import com.ruiysoft.controller.sys.res.SlideModelResponse;
import com.ruiysoft.controller.sys.res.UserResponse;
import com.ruiysoft.entity.sys.*;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.security.entity.EntryUser;
import com.ruiysoft.service.integral.IIntegralService;
import com.ruiysoft.service.sys.ISysShopPersonnelRelationService;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-11-02T18:10:17.406+08:00")

@RestController
public class MicroprogramApiController implements MicroprogramApi {

    private static final Logger log = LoggerFactory.getLogger(MicroprogramApiController.class);

    private final ObjectMapper objectMapper;

    @Autowired
    IIntegralService integralService;


    @Resource
    MicroprogramApiService microprogramApiService;

    @org.springframework.beans.factory.annotation.Autowired
    public MicroprogramApiController(ObjectMapper objectMapper, HttpServletRequest request) {
        this.objectMapper = objectMapper;
    }

    @Resource
    ISysShopPersonnelRelationService iSysShopPersonnelRelationService;

    @Override
    public Result<Void> deleteShopDesignById(@ApiParam(value = "", required = true) @PathVariable("id") Long id, HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
            microprogramApiService.deleteShopDesignById(microShop.getId(), id);
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

    @Override
    public Result<List<BrowsedShopResponse>> getBrowsedShops(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
                if (null == personnel) {
                    return ResultGenerator.genFailResult("未获取到人员信息");
                }
                System.out.println("獲取到登陸用戶:" + JSON.toJSONString(personnel));
                List<BrowsedShopResponse> responses = microprogramApiService.getBrowsedShops(personnel.getId());
                return ResultGenerator.genSuccessResult(responses);
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }

        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

    @Override
    public Result<Void> delBrowsedShop(@ApiParam(value = "店铺主键") @RequestParam(value = "shopId", required = true) @Valid Long shopId, HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
                microprogramApiService.delBrowsedShop(personnel.getId(), shopId);
                return ResultGenerator.genSuccessResult();
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }
        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

    @Override
    public Result<Void> chooseBrowsedShop(@ApiParam(value = "店铺主键") @Valid @RequestParam(value = "shopId", required = true) Long shopId) {

        try {
            EntryUser user = LoginContextUtil.instance().getEntryUser();
            microprogramApiService.chooseBrowsedShop(user.getLoginType(), null == user.getSysUser() ? null : user.getSysUser().getId(), null == user.getPersonnel() ? null : user.getPersonnel().getId(), shopId);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("Couldn't serialize response for content type application/json", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

//    @Cacheable(value = "getLoginOnUser", key = "#p0")
    @Override
    public Result<UserResponse> getLoginOnUser(@RequestHeader(value="Authorization", defaultValue = "0") String authorization) {
        try {
            EntryUser user = LoginContextUtil.instance().getEntryUser();
            SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
            SysUserShopRelation relation = ((null == user.getSysUser()) ? null : microprogramApiService.getSysUserShopRelationByUserIdAndShopId(user.getSysUser().getId(), shop.getId()));

            UserResponse response = new UserResponse()
                    .identity(null == relation ? IdentityConst.ORDINARY_USER : IdentityConst.SHOPKEEPER)
                    .mobile(user.getPersonnel().getMobile())
                    .setPersonnelId(user.getPersonnel().getId())
                    .setRealName(user.getPersonnel().getRealName())
                    .setShopId(shop.getId())
                    .setUserName(user.getSysUser() != null ? user.getSysUser().getUserName() : "");


            return ResultGenerator.genSuccessResult(response);

        } catch (Exception e) {
            log.error("Couldn't serialize response for content type application/json", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }

    }

//    @Cacheable(value = "getEntryShop", key = "#p0")
    @Override
    public Result<ShopResponse> getEntryShop(@RequestHeader(value="Authorization", defaultValue = "0") String authorization) {
        try {
            SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
            List<SysShopModuleRelation> relationList = microprogramApiService.getShopModuleByShopId(shop.getId());
            return ResultGenerator.genSuccessResult(new ShopResponse().id(shop.getId()).shopName(shop.getShopName())
                    .shopImg(shop.getShopImg())
                    .brandIntroduction(shop.getBrandIntroduction())
                    .officialWebsite(shop.getOfficialWebsite())
                    .telephone(shop.getTelephone())
                    .shopAddress(shop.getShopAddress())
                    .setVipLeve(shop.getVipLevel())
                    .setExpiryTime(shop.getExpiryTime())
                    .setModuleList(relationList));
        } catch (Exception e) {
            log.error("Couldn't serialize response for content type application/json", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<List<SysShopModuleRelation>> getShopModule(HttpServletRequest request) {
        try {
            SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
            List<SysShopModuleRelation> relations = microprogramApiService.getShopModuleByShopId(microShop.getId());
            return ResultGenerator.genSuccessResult(relations);
        }catch (Exception e){
            log.error("error", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }

    }

    @Override
    public Result<List<ShopDesignDto>> getShopDesign(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
                List<ShopDesignDto> rDtos = microprogramApiService.getShopDesignByShopId(microShop.getId());
                return ResultGenerator.genSuccessResult(rDtos);

            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }
        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

    @Override
    public Result<ShopDesignDto> getShopDesignById(@ApiParam(value = "店铺设计主键 ", required = true) @PathVariable("id") Long id, HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
                ShopDesignDto dto = microprogramApiService.getShopDesignById(microShop.getId(), id);
                return ResultGenerator.genSuccessResult(dto);
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }

        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

    @Override
    public Result<ShopDistributionDto> getShopDistribution(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
                ShopDistributionDto dto = microprogramApiService.getShopDistributionByShopId(microShop.getId());
                return ResultGenerator.genSuccessResult(dto);
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }

        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

//    @Cacheable(value = "getSlideModelByShopId", key = "#p0")
    @Override
    public Result<List<SlideModelResponse>> getSlideModelByShopId(@RequestHeader(value="Authorization", defaultValue = "0") String authorization) {
        try {
            SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
            List<SlideModelResponse> responses = microprogramApiService.getSlideModelByShopId(microShop.getId());
            return ResultGenerator.genSuccessResult(responses);
        } catch (Exception e) {
            log.error("Couldn't serialize response for content type application/json", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<String> register(@ApiParam(value = "注册", required = true) @Valid @RequestBody UserDto userDto, HttpServletRequest request) {
        try {
            // 从缓存读取信息
            EntryUser user = LoginContextUtil.instance().getEntryUser();
            //fixme 暂时这样处理，因为不要求输入手机号\密码\用户名\真实姓名等
            if (StringUtils.isEmpty(userDto.getMobile())) {
                userDto.setMobile(String.format("%011d", user.getPersonnel().getId()));
            }
            if (StringUtils.isEmpty(userDto.getPassword())) {
//                userDto.setPassword(String.format("%06d", user.getPersonnel().getId()));
                userDto.setPassword("123456");
            }
            //if(StringUtils.isEmpty(userDto.getUsername())){
            userDto.setUsername(userDto.getMobile());
            //}
            if (StringUtils.isEmpty(userDto.getRealName())) {
                userDto.setRealName(user.getPersonnel().getNickname());
            }

            //System.out.println( JSON.toJSONString(user));
            Long shopId = microprogramApiService.register(userDto, user.getLoginType());
            return ResultGenerator.genSuccessResult(shopId.toString());
        } catch (Exception e) {
            log.error("register error", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> updateShopById(@ApiParam(value = "Updated shop object", required = true) @Valid @RequestBody ShopDto shop, HttpServletRequest request) {
        try {
            SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
            microprogramApiService.updateShopById(microShop.getId(), shop);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("updateShopById error", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> updateShopDesignById(@ApiParam(value = "id that need to be updated", required = true) @PathVariable("id") Long id,
                                             @ApiParam(value = "Updated shop object", required = true) @Valid @RequestBody ShopDesignDto shopDesign,
                                             HttpServletRequest request) {

        try {
            SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
            microprogramApiService.updateShopDesignById(microShop.getId(), shopDesign);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("Couldn't serialize response for content type application/json", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }

    }

    @Override
    public Result<Void> addShopDesign(@ApiParam(value = "Updated shop object", required = true) @RequestBody @Valid ShopDesignDto shopDesign, HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
                microprogramApiService.addShopDesign(microShop.getId(), shopDesign);
                return ResultGenerator.genSuccessResult();
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }

        }
        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

    @Override
    public Result<PreorderResponse> preorder(@ApiParam(value = "", required = true) @Valid @RequestBody PreorderDto preorder, HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
                SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
                SysShopPrice price = microprogramApiService.getSysShopPriceByNum(preorder.getTime());
                if (null == price) {
                    return ResultGenerator.genFailResult("购买期限不正确!");
                }
                PreorderResponse response = microprogramApiService.preorder(microShop.getId(), personnel.getId(), price.getNum(), price.getPrice());
                return ResultGenerator.genSuccessResult(response);
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }

        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

//    @Override
//    public Result<JsSignResponse> pay(@ApiParam(value = "", required = true) @PathVariable String orderNo) {
//        String accept = request.getHeader("Accept");
//        if (accept != null && accept.contains("application/json")) {
//            try {
//                SysMicroShop microShop = LoginContextUtil.instance().getSysMicroShop();
//                SysShopPersonnel personnel = LoginContextUtil.instance().getSysShopPersonnel();
//                SysTransactionRecord record = microprogramApiService.getSysTransactionRecord(orderNo);
//                SysShopPrice price = microprogramApiService.getSysShopPriceByNum(record.getPurchaseTime());
//                if (null == price){
//                    return ResultGenerator.genFailResult("购买期限不正确!");
//                }
//                PreorderResponse response = microprogramApiService.preorder(microShop.getId(),personnel.getId(),price.getNum(),price.getPrice());
//                return ResultGenerator.genSuccessResult(response);
//            } catch (Exception e) {
//                log.error("Couldn't serialize response for content type application/json", e);
//                return ResultGenerator.genFailResult(e.getMessage());
//            }
//        }
//
//        return ResultGenerator.genAcceptResult("accept is :" +accept);
//    }

    @Override
    public Result<Void> updateWechatInfo(@ApiParam(value = "", required = true) @RequestBody @Valid WeChatInfoDto dto, HttpServletRequest request) {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        SysShopPersonnel newPersonnel = new SysShopPersonnel();
        newPersonnel.setId(personnel.getId());
        newPersonnel.setNickname(dto.getNickname());
        newPersonnel.setHeadImgUrl(dto.getHeadImgUrl());
        microprogramApiService.updatePersonnelById(newPersonnel);
        return ResultGenerator.genSuccessResult();
    }

//    @Override
//    public Result<Void> setMember(ApiParam(value = "", required = true) @RequestBody @Valid List<SysShopPersonnelRelation> relations, HttpServletRequest request) {
//        try {
//            log.info(JSON.toJSONString(relations));
//            microprogramApiService.updateShopPersonnelRelation(relations);
//            return ResultGenerator.genSuccessResult();
//        } catch (Exception e) {
//            log.error("MicroprogramApiController setMember: {}", e);
//        }
//        return ResultGenerator.genFailResult("出错了");
//    }

    @Override
    public Result<Void> updatePersonnel(@ApiParam(value = "", required = true) @RequestBody @Valid Map<String, Object> dto, HttpServletRequest request) {
        SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();

        SysShopPersonnel newPersonnel = new SysShopPersonnel();
        newPersonnel.setId(personnel.getId());
        newPersonnel.setMobile(String.valueOf(dto.get("mobile")));
        newPersonnel.setRealName(String.valueOf(dto.get("realName")));

        microprogramApiService.updatePersonnelById(newPersonnel);

        // 绑定手机同时开通积分功能
        IntegralRechargeVo integralRechargeVo = new IntegralRechargeVo();
        integralRechargeVo.setIntegral(0l);
        integralRechargeVo.setPhone(newPersonnel.getMobile());
        integralService.recharge(integralRechargeVo, microShop.getId());

        // 绑定手机号设置成1级会员，后续可改成购买1,2,3级会员
        SysShopPersonnelRelation sysShopPersonnelRelation = iSysShopPersonnelRelationService.selectByShopIdAndPersonnelId(microShop.getId(), personnel.getId());
        if(sysShopPersonnelRelation != null) {
            sysShopPersonnelRelation.setMemberFlag(true);
            sysShopPersonnelRelation.setMemberLevel(1);
            iSysShopPersonnelRelationService.updateById(sysShopPersonnelRelation);
        }

        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result<Void> setMember(@ApiParam(value = "", required = true) @Valid @RequestBody List<SysShopPersonnelRelation> relations, HttpServletRequest request) {
        try {
            log.info(JSON.toJSONString(relations));
            microprogramApiService.updateShopPersonnelRelation(relations);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("MicroprogramApiController setMember: {}", e);
        }
        return ResultGenerator.genFailResult("出错了");
    }

    @Override
    public Result<Void> setDistributionRelation(@ApiParam(value = "", required = true) @Valid @RequestBody SysShopPersonnelRelation relation, HttpServletRequest request) {
        try {
            log.info(JSON.toJSONString(relation));
            microprogramApiService.setDistributionRelation(relation);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("MicroprogramApiController setMember: {}", e);
        }
        return ResultGenerator.genFailResult("出错了");
    }

    @Override
    public Result<Void> setDistributionIdToUser(@Valid SysShopPersonnelRelation relation, HttpServletRequest request) {
        try {
            log.info(JSON.toJSONString(relation));
            microprogramApiService.setDistributionIdToUser(relation);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("MicroprogramApiController setMember: {}", e);
        }
        return ResultGenerator.genFailResult("出错了");
    }

    @Override
    public Result<SysShopDistribution> getDistributionIdByUser() {
        SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        SysShopDistribution shopDistribution = microprogramApiService.getDistributionIdByUser(microShop.getId(),personnel.getId());
        if(shopDistribution != null)
            return ResultGenerator.genSuccessResult(shopDistribution);

        return ResultGenerator.genFailResult("出错了");
    }

    @Override
    public Result<PageInfo<ShopPersonnelResponse>> shopPersonnels(@NotNull @ApiParam(value = "分页页码", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页条数", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                //List<ShopPersonnelResponse> res = new ArrayList<>();
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
//                SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
                Page<SysShopPersonnel> page = microprogramApiService.getShopPersonnel(microShop.getId(), pageStart, pageSize);
                if (page.getRecords().isEmpty()) {
                    return ResultGenerator.genSuccessResult();
                }

                List<ShopPersonnelResponse> res = page.getRecords().stream().map(e -> {
                    ShopPersonnelResponse spr = new ShopPersonnelResponse()
                            .setPersonnelId(e.getId())
                            .setShopPersonnelRelationId(e.getRelationId())
                            .setNickname(e.getNickname())
                            .setHeadImgUrl(e.getHeadImgUrl())
                            .setCreateTime(e.getCreateTime())
                            .setMemberFlag(e.getMemberFlag())
                            .setMemberLevel(e.getMemberLevel())
                            .setMobile(e.getMobile())
                            .setRealName(e.getRealName());

                    spr.setIntegral(e.getIntegral());

                    return spr;

                }).collect(Collectors.toList());

                return ResultGenerator.genSuccessResult(new PageInfo<ShopPersonnelResponse>(res, page));

            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }

        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }
    @Override
    public Result<PageInfo<ShopPersonnelResponse>> selectPersonnelRalationList(@NotNull @ApiParam(value = "分页页码", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页条数", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
                Page<SysShopPersonnel> page = microprogramApiService.selectPersonnelRalationList(microShop.getId(), pageStart, pageSize);
                if (page.getRecords().isEmpty()) {
                    return ResultGenerator.genSuccessResult();
                }
                List<ShopPersonnelResponse> res = page.getRecords().stream().map(e -> {
                    ShopPersonnelResponse spr = new ShopPersonnelResponse()
                            .setPersonnelId(e.getId())
                            .setShopPersonnelRelationId(e.getRelationId())
                            .setNickname(e.getNickname())
                            .setHeadImgUrl(e.getHeadImgUrl())
                            .setCreateTime(e.getCreateTime())
                            .setMemberFlag(e.getMemberFlag())
                            .setMemberLevel(e.getMemberLevel())
                            .setMobile(e.getMobile())
                            .setRealName(e.getRealName()).setDistributionId(e.getDistributionId()).setDistributionName(e.getDistributionName());

                    spr.setIntegral(e.getIntegral());

                    return spr;

                }).collect(Collectors.toList());

                return ResultGenerator.genSuccessResult(new PageInfo<ShopPersonnelResponse>(res, page));

            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }

        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

    @Override
    public Result<List<SysShopPrice>> getSysShopPrice(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                List<SysShopPrice> response = microprogramApiService.getSysShopPrice();
                return ResultGenerator.genSuccessResult(response);
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }

        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }

    @Override
    public Result<SysShopPersonnel> getPersonnelById(@ApiParam(value = "人員信息主键", required = true) @PathVariable("id") Long id, HttpServletRequest request) {

        try {
            SysShopPersonnel response = microprogramApiService.getShopPersonnelById(id);
            response.setOpenid(null);
            return ResultGenerator.genSuccessResult(response);
        } catch (Exception e) {
            log.error("Couldn't serialize response for content type application/json", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Object getPersonnelByParentId(@ApiParam(value = "店铺主键", required = true) @Valid @RequestParam(value = "shopId", required = true)Long shopId, @ApiParam(value = "人員信息主键", required = true) @Valid @RequestParam(value = "id", required = true)Long id,@NotNull @ApiParam(value = "分页页码", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页条数", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, HttpServletRequest request) {
        try {
            Page<SysShopPersonnel> personnelByParentId = microprogramApiService.getPersonnelByParentId(shopId, id, pageStart, pageSize);
          //  SysShopPersonnel response = null;
          //  response.setOpenid(null);
            return personnelByParentId;
        } catch (Exception e) {
            log.error("Couldn't serialize response for content type application/json", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Object getVisitorList() {
        return ResultGenerator.genSuccessResult(microprogramApiService.getShopVisitorList());
    }

    private Long getUserId() {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        return personnel.getId();
    }

    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }



    @Override
    public Object getDistributionerListByParentId(Integer pageStart, Integer pageSize) {
        Long shopId = this.getShopId();
        Long personnelId = this.getUserId();

        try {
            Page<SysShopPersonnel> personnelByParentId = microprogramApiService.getPersonnelByParentId(shopId, personnelId, pageStart, pageSize);
            return personnelByParentId;

        } catch (Exception e) {
            log.error("Couldn't serialize response for content type application/json", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Object getCurrentDistributionerList(Integer pageStart, Integer pageSize) {
        Long shopId = this.getShopId();
        Long userId= this.getUserId();
        Page page= microprogramApiService.getCurrentDistributionerList(shopId,userId,pageStart,pageSize);
        return page;
    }

    @Override
    public Result<Void> settleCommissionByIds(@RequestBody Map<String,Object> ids)
    {
        List<String> is= (List<String>) ids.get("ids");
        String remarks= (String) ids.get("remarks");
        Long shopId = this.getShopId();
        boolean u= microprogramApiService.settleCommissionByIds(shopId,is,remarks);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Object getRelationCommissionList(@NotNull @ApiParam(value = "分页页码", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页条数", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, HttpServletRequest request) {
        Long shopId = this.getShopId();
        Page page= microprogramApiService.getRelationCommissionList(shopId,pageStart,pageSize);
        return page;
    }

    @Override
    public Object getRelationCommissionByUserId(@NotNull @ApiParam(value = "分页页码", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页条数", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize,@NotNull @ApiParam(value = "用户ID", required = true) @Valid @RequestParam(value = "userId", required = true) Long userId, HttpServletRequest request) {
        Long shopId = this.getShopId();
        Page page= microprogramApiService.getRelationCommissionByUserId(shopId,userId,pageStart,pageSize);
        return page;
    }
    @Override
    public Object getRelationCommissionByBuyerId(@NotNull @ApiParam(value = "分页页码", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页条数", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize,@NotNull @ApiParam(value = "用户ID", required = true) @Valid @RequestParam(value = "userId", required = true) Long userId, HttpServletRequest request) {
        Long shopId = this.getShopId();
        Long id = this.getUserId();
        Page page= microprogramApiService.getRelationCommissionByBuyerId(shopId,userId,pageStart,pageSize,id);
        return page;
    }
    @Override
    public Object getRelationCommissionDisByUserId(@NotNull @ApiParam(value = "分页页码", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页条数", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize,@NotNull @ApiParam(value = "用户ID", required = true) @Valid @RequestParam(value = "userId", required = true) Long userId, HttpServletRequest request) {
        Long shopId = this.getShopId();
        Page page= microprogramApiService.getRelationCommissionDisByUserId(shopId,userId,pageStart,pageSize);
        return page;
    }

    @Override
    public Result<SysShopDistribution> getDistributionById(Long id, HttpServletRequest request) {
        try {
            SysShopDistribution response = microprogramApiService.getDistributionById(id);
            return ResultGenerator.genSuccessResult(response);
        } catch (Exception e) {
            log.error("Couldn't serialize response for content type application/json", e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }
    @Override
    public Result<Integer> deleteShopDistribution(Long id, HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
                int i= microprogramApiService.deleteShopDistribution(id);
                return ResultGenerator.genSuccessResult(i);
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }

        }
        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }
    @Override
    public Result<List<SysShopDistribution>> getShopDistributionList(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
                List<SysShopDistribution> dto = microprogramApiService.getShopDistributionListByShopId(microShop.getId());
                return ResultGenerator.genSuccessResult(dto);
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }
        }

        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }
    @Override
    public Result<Void> updateShopDistribution(@ApiParam(value = "", required = true) @Valid @RequestBody SysShopDistribution distribution, HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            try {
                SysMicroShop microShop = LoginContextUtil.instance().getEntryMicroShop();
                microprogramApiService.updateShopDistribution(microShop.getId(), distribution);
                return ResultGenerator.genSuccessResult();
            } catch (Exception e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return ResultGenerator.genFailResult(e.getMessage());
            }

        }
        return ResultGenerator.genAcceptResult("accept is :" + accept);
    }
}

